package com.example.userpage.controller;

import com.example.userpage.model.ImageUploadRequest;
import com.example.userpage.model.ResponseMessage;
import com.example.userpage.service.ImageUploadService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/userpage")
public class UserPageController {

    @Autowired
    private ImageUploadService imageUploadService;

    @PostMapping("/sendpic")
    public ResponseMessage uploadImage(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam("metadata") String metadata) throws IOException {
        String ip = getClientIp(request);
        ImageUploadRequest imageUploadRequest = new ObjectMapper().readValue(metadata, ImageUploadRequest.class);
        return imageUploadService.handleImageUpload(ip, imageUploadRequest, file);
    }

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // X-Forwarded-For 可能是：client, proxy1, proxy2
            // 取第一个非 unknown 的值
            String[] parts = ip.split(",");
            for (String part : parts) {
                part = part.trim();
                if (part.length() != 0 && !"unknown".equalsIgnoreCase(part)) {
                    return part;
                }
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        // 最后退回到远端地址
        return request.getRemoteAddr();
    }
}
